/**
 * Created by huhai on 17/9/27.
 */

import React, { PropTypes } from 'react';
import  Tabs  from 'antd/lib/tabs';
import 'antd/lib/tabs/style/css'
const TabPane = Tabs.TabPane;
import style from './style.scss'
import Modal from 'antd/lib/modal';
import Icon from 'antd/lib/icon';
import Button from 'antd/lib/button';
import Notification from 'antd/lib/notification';
import Alert from 'antd/lib/alert'
import 'antd/lib/modal/style/css';
import 'antd/lib/button/style/css';
import 'antd/lib/message/style/css';
import 'antd/lib/switch/style/css';
import 'antd/lib/notification/style/css';
import 'antd/lib/menu/style/css';
import 'antd/lib/alert/style/css';
import 'antd/lib/badge/style/css';
import 'antd/lib/input/style/css';
import 'antd/lib/modal/style/css';
import 'antd/lib/form/style/css';
import 'antd/lib/input/style/css';

import _ from 'lodash'
import message from 'antd/lib/message';
import SortableComponent from './sortList'
import {isNum} from '../../common/utils'
import EditModule from './editModule'
import AddNewModule from './addNewModule'

//container for hospital-tree & hospital-show
export default class TemplateManagment extends React.Component{

  state={
    style: 0,
    activeKey:"",
    templateModify: false,
    selectedModule: '',
    visiableAddNew: false
  };

  exchangeModulePosition(moduleID, oldIndex, newIndex){
   let curTemplate = _.find(this.props.templatesInfo.templates, {"templateID":parseInt(moduleID)})
    let cloneCurModule = _.cloneDeep(curTemplate);

  }
  templateModifyTrue(){
    this.setState({templateModify: true})
  }
  templateModifyFalse(){
    this.setState({templateModify: false})
  }
  tabClick=(index)=>{
    //如果位于当前模板
    if(parseInt(index) === parseInt(this.state.activeKey)){
      return
    }
    //检查是否应该跳转(已经有改动)
    if(this.state.templateModify){
      Modal.confirm({
        title: '请确认',
        content: `当前配置已经修改，你要丢弃当前修改吗？`,
        okText: '是的',
        cancelText: '取消',
        onOk: this.confirmSHIFT.bind(this, index)
      })
    }else{
      this.confirmSHIFT(index)
    }

  }
  confirmSHIFT(index){
    let goTotemplate = _.find(this.props.templatesInfo, {"templateID":parseInt(index)})
    if(goTotemplate){
      Notification.warning({
        message:  `请注意！您即将配置${goTotemplate.templateName}!`,
      });
      // Modal.info({
      //   content: `您即将配置${goTotemplate.templateName}!`,
      //   okText: '确认',
      //   cancelText: '取消',
      //   onOk: this.switchSure.bind(this, index)
      // })
      this.switchSure(index)
    }else{
      Notification.warning({
        message:  `没有找到对应的模板,id为:${index}`,
      });
    }

  }
  switchSure(index){
      if(parseInt(index) === parseInt(this.state.activeKey)){
        return
      }else{
        this.setState({activeKey: index, selectedModule: ''},()=>{
          this.templateModifyFalse()
        })
      }
      this.setState({style: index < 4 ? 0 : 1})
      this.props.CHECK_CHART({hosId: this.props.match.params.id, style: index < 4 ? 0 : 1})
  }
  showModal(){
    this.setState({visiableAddNew: true})
  }
  hideModal(){
    this.setState({visiableAddNew: false})
  }
  componentDidMount(){
    //fetch data
   this.props.GET_TEMPLATES({hosId: this.props.match.params.id}).then(()=>{
     //set default page
     let curActiveKey = parseInt(this.state.activeKey);
     let firstPage = (this.props.templatesInfo.length !==0) ? this.props.templatesInfo[0].templateID : ''
     let activePageId = (typeof curActiveKey === 'number' && !isNaN(curActiveKey)) ? curActiveKey : parseInt(firstPage)
     isNum(firstPage) && this.setState({activeKey: activePageId},()=>{
       console.log("初始加载完毕的page为", activePageId)
       // this.cacheCur
     });
     //show modules
     this.checkChart()
   })
  }
  curSelectModule(module){
    this.setState({selectedModule: module})
  }
  exportPDF(){
    let templateID = this.state.activeKey
    let HospitalId = this.props.match.params.id
    if(templateID == 4) {
      window.open(`http://121.42.252.26:3001/horizontal/${HospitalId}?template=${templateID}&style=1`, "_blank")
    }
    if(templateID == 1 || templateID == 2 || templateID == 3){
      window.open(`http://121.42.252.26:3001/${HospitalId}?template=${templateID}&style=0`, "_blank")
    }
  }
  previewWeb(){
    let templateID = this.state.activeKey
    let HospitalId = this.props.match.params.id
    if(templateID == 4) {
      window.open(`http://121.42.252.26:3000/horizontal/${HospitalId}?template=${templateID}&style=1`, "_blank")
    }
    if(templateID == 1 || templateID == 2 || templateID == 3){
      window.open(`http://121.42.252.26:3000/${HospitalId}?template=${templateID}&style=0`, "_blank")
    }
  }
  clearDataOk () {
    const result = this.props.CLEAR_DAYA({hosId: this.props.match.params.id, style: this.state.style})
    result.then(res => {
      if (!res.payload) {
        Notification.error({
          message: '同步失败！',
          description: '服务当前不可用'
        });
        return false
      }
      if (res.payload.data.success) {
        Notification.success({
          message: '清除数据成功'
        });
        this.checkChart()
        if ((this.state.selectedModule || {}).id) {
          this.props.GET_MODULE_DATA({
            hosId:this.props.match.params.id,
            page:this.state.selectedModule.id,
            style:this.state.style
          })
        }
      }
      else {
        Notification.error({
          message: '同步失败！',
          description: '服务当前不可用'
        });
      }
    })
  }
  clearData () {
    Modal.confirm({
      title: '清除数据',
      content: `是否要清除当前医院所有修改的数据？清除后不可恢复`,
      okText: '是的',
      cancelText: '取消',
      onOk: this.clearDataOk.bind(this)
    })
  }
  checkChart () {
    this.props.CHECK_CHART({hosId: this.props.match.params.id, style: this.state.style})
  }
  render(){
    let HospitalId = this.props.match.params.id
    let {templatesInfo} =this.props;
    let hasTemps = (templatesInfo.length !==0) ? true : false
    let templates = templatesInfo
    let curTemplate = _.find(templates,{templateID: parseInt(this.state.activeKey)})
    return (
      <div>
        <Alert message={this.props.checkChart} type="info"  style={{marginTop: '20px'}} showIcon />
        {hasTemps && <div className={style.marginTop20}>
          <div>
            <Tabs onTabClick={this.tabClick.bind(this)}
                  activeKey={''+this.state.activeKey}
                  size="default"
                  type={"card"}>
              {templates && templates.map((obj)=>{
                return <TabPane
                  tab={obj.templateName}
                  key={obj.templateID}   />
              })}
            </Tabs>
          </div>
        </div>}

        <div className={style.tab_content}>
          <div className="modules_list">
           <div>
             {curTemplate && <SortableComponent sync={this.props.SYNC_MODULES_IN_TEMPLATES}
                                                templateID={this.state.activeKey}
                                                HospitalId={HospitalId}
                                                templateName={curTemplate.templateName}
                                                exchangeModulePosition={this.exchangeModulePosition}
                                                curModules={curTemplate.modules}
                                                templateModifyTrue={this.templateModifyTrue.bind(this)}
                                                templateModifyFalse={this.templateModifyFalse.bind(this)}
                                                templateModify={this.state.templateModify}
                                                selectedModule={this.curSelectModule.bind(this)}
                                                reFetchData={this.componentDidMount.bind(this)}
             />}
           </div>
          </div>
          <div className="modules_content">

            {hasTemps && !this.state.selectedModule && <div className={style.edit} style={{ marginTop: 100, marginBottom: 100}}>
              <Icon type="edit" style={{ fontSize: 100, color: '#e2e2e2' }}/>
              <div>
                点击左侧模块，进行编辑操作
              </div>
            </div>}
            {this.state.selectedModule && <EditModule module={this.state.selectedModule}
                                                      templateID={this.state.activeKey}
                                                      moduleDetail={this.props.moduleDetail}
                                                      moduleData={this.props.moduleData}
                                                      moduleOldData={this.props.moduleOldData}
                                                      getModuleDetail={this.props.GET_MODULE_DETAIL}
                                                      getModuleData={this.props.GET_MODULE_DATA}
                                                      saveTextArea={this.props.SAVE_TEXTAREA}
                                                      saveDataArea={this.props.SAVE_DATAAREA}
                                                      syncTextArea={this.props.SYNC_TEXTAREA}
                                                      syncDataArea={this.props.SYNC_DATAAREA}
                                                      templateModifyTrue={this.templateModifyTrue.bind(this)}
                                                      templateModifyFalse={this.templateModifyFalse.bind(this)}
                                                      HospitalId={HospitalId}
                                                      checkChart={this.checkChart.bind(this)}


            />}


          </div>
        </div>
        <div className={style.actions}>
          <Button type="primary" icon="file" onClick={this.clearData.bind(this)}> 清除改动数据 </Button>
          {(!isNaN(parseInt(this.state.activeKey))) && <Button type="primary" icon="file"  onClick={this.exportPDF.bind(this)} > 导出PDF </Button> }
          {(!isNaN(parseInt(this.state.activeKey))) && <Button type="primary" icon="file"  onClick={this.previewWeb.bind(this)} > 预览网页 </Button> }
          <Button type="primary" icon="plus"  onClick={this.showModal.bind(this)} > 新增模块 </Button>
          <AddNewModule visiableAddNew={this.state.visiableAddNew} hideModal={this.hideModal.bind(this)} addNewModule={this.props.ADD_NEW_MODULE}/>
        </div>
      </div>
    )
  }
}
